import { Injectable } from '@angular/core';
import {
  Http,
  Response,
  URLSearchParams,
  Headers,
  RequestOptions,
  RequestOptionsArgs
} from '@angular/http';

import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { environment } from '../../../environments/environment';
import { HttpService } from './auth.service';
import { LoginService } from './login.service';


@Injectable()
export class MaterialManageService {
    private apiBaseUrl = environment.apiBaseUrl;

    constructor (
        private loginService: LoginService,
        private http: Http,
        private myHttp: HttpService,
    ) {}
    // http://47.100.161.202:8080/admin/channel/list
    // 获取标签列表
    getmaterialList(param: object): Observable<object> {
        const params: URLSearchParams = new URLSearchParams();
        params.set('name', param['labelName']);
        params.set('pageSize', param['pageSize']);
        params.set('pageNumber', param['pageNumber']);
        return this.http.get(this.apiBaseUrl + 'admin/material/list', { params: params })
                .map(this.extractData)
                .catch(this.handleError);
    }

    // 根据商品编号从又乐查询商品接口
    getProductList(param: object): Observable<object> {
        const params = {};
        let pamUrl = '?searchValue=' + param['productNo'];
        let tokenPam = '&token=' + this.loginService.user.token;
        return this.myHttp.get(this.apiBaseUrl + 'admin/material/getProductList' + pamUrl + tokenPam)
    }

    // 根据名称获取原料接口
    findByName(name): Observable<object> {
        const params = new URLSearchParams();
        params.append('name', name);
        return this.http.get(this.apiBaseUrl + 'admin/material/findByName', {params})
                .map(this.extractData)
                .catch(this.handleError);
    }

    // 新增原料接口
    postCreatematerial(param: object): Observable<object> {
        const data = new URLSearchParams();
        data.append('name', param['name']);
        data.append('unit', param['unit']);
        param['materialGoods'].forEach((mat, index) => {
            data.append(`materialGoods[${index}].goods.id`, mat['id']);
            data.append(`materialGoods[${index}].recomflag`, mat['recomflag']);
            data.append(`materialGoods[${index}].dosage`, mat['dosage']);
            data.append(`materialGoods[${index}].order`, mat['order']);
        });
        return this.http.post(this.apiBaseUrl + 'admin/material/save', data)
            .map(res => res.text() ? res.json() : {})
            .catch(this.handleError);
    }

    // 修改原料接口
    postUpdatematerial(param: object): Observable<object> {
        const data = new URLSearchParams();
        data.append('id', param['id']);
        data.append('name', param['name']);
        data.append('unit', param['unit']);
        param['materialGoods'].forEach((mat, index) => {
            data.append(`materialGoods[${index}].goods.id`, mat['id']);
            data.append(`materialGoods[${index}].recomflag`, mat['recomflag']);
            data.append(`materialGoods[${index}].dosage`, mat['dosage']);
            data.append(`materialGoods[${index}].order`, mat['order']);
        });
        return this.http.post(this.apiBaseUrl + 'admin/material/save', data)
            .map(res => res.text() ? res.json() : {})
            .catch(this.handleError);
    }
    // 删除原料接口
    postDeleteChannel(param: object): Observable<object> {
        const data = new URLSearchParams();
        let paramUrl = '';
        param['ids'].forEach((pm, index) => {
            if ((index + 1) === param['ids'].length) {
                paramUrl += pm;
            } else {
                paramUrl += pm + ',';
            }
        });
        data.append(`ids`, paramUrl);
        return this.http.post(this.apiBaseUrl + 'admin/material/delete', data)
            .map(res => res.text() ? res.json() : {})
            .catch(this.handleError);
    }

    private extractData(res: Response) {
        const body = res.json();
        return body || { };
    }

    private handleError (error: Response | any) {
        return Observable.throw(error);
    }
}
